import os
import time

from appium import webdriver
from appium.options.common import AppiumOptions
from appium.webdriver.common.appiumby import AppiumBy
from selenium.common import NoSuchElementException
from faker import Faker
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

fake = Faker('zh_CN')
name = fake.name()
phone_number = fake.phone_number()


class Testweixinwork:

    def setup(self):
        # 配置启动参数
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '12'
        desired_caps['deviceName'] = '127.0.0.1:7555'
        desired_caps['udid'] = '127.0.0.1:7555'
        desired_caps['newCommandTimeout'] = 60
        desired_caps['noReset'] = True
        #配置参数老控制app启动关闭
        desired_caps["appium:forceAppLaunch"] = True
        desired_caps["appium:shouldTerminateApp"] = True

        desired_caps["automationName"] = 'uiautomator2'
        # desired_caps["dontStopAppOnReset"] = True
        desired_caps["adbExecTimeout"] = 30000
        # com.android.settings/com.android.settings.Settings
        desired_caps['appPackage'] = 'com.tencent.wework'
        desired_caps['appActivity'] = 'com.tencent.wework.launch.LaunchSplashActivity'
        options = AppiumOptions().load_capabilities(desired_caps)
        # server 版本启动地址：http://127.0.0.1:4723
        # gui 版本启动地址：http://127.0.0.1:4723/wd/hub
        self.driver = webdriver.Remote('http://127.0.0.1:4723', options=options)

    def teardown(self):

        self.driver.quit()

    def test_add_success(self):
        # 点击通讯录
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='通讯录']").click()
        self.swipe_find(element="//*[@text='添加成员']").click()
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='手动输入添加']").click()
        # 姓名输入框
        self.driver.find_elements(AppiumBy.ID, "com.tencent.wework:id/au0")[0].send_keys(name)
        # 性别输入框
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='性别']/following-sibling::*").click()
        # 性别选择
        self.driver.find_elements(AppiumBy.ID, "com.tencent.wework:id/b2x")[0].click()
        # 手机号输入框
        self.driver.find_element(AppiumBy.ID, "com.tencent.wework:id/eq7").send_keys(phone_number)
        # 点击保存
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='保存']").click()
        # 获取 toast 展示之后的 pagesource
        # print(self.driver.page_source)
        # 获取toast文本
        tips = WebDriverWait(self.driver, 10).until(expected_conditions.presence_of_element_located(
            (AppiumBy.XPATH, "//*[@class='android.widget.Toast']"))).text
        print(tips)
        # assert tips=="添加成功"
        # 点击返回
        self.driver.find_element(AppiumBy.XPATH, "//*[@resource-id='com.tencent.wework:id/gu_']").click()
        time.sleep(2)
        # 点击搜索
        self.driver.find_element(AppiumBy.ID, "com.tencent.wework:id/guu").click()
        # 搜索输入框
        self.driver.find_element(AppiumBy.ID, "com.tencent.wework:id/fk1").send_keys(name)
        # 获取搜索后的信息
        text = WebDriverWait(self.driver, 10).until(expected_conditions.presence_of_element_located(
            (AppiumBy.XPATH, "//*[@resource-id='com.tencent.wework:id/dqe']/child::*"))).text
        print("==>", text, phone_number)
        # 点击返回
        self.driver.find_element(AppiumBy.XPATH, "//*[@resource-id='com.tencent.wework:id/gu_']").click()
        assert text == name

    def test_add_fail(self):
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='通讯录']").click()
        self.swipe_find(element="//*[@text='添加成员']").click()
        time.sleep(1)
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='手动输入添加']").click()
        # 姓名输入框
        self.driver.find_elements(AppiumBy.ID, "com.tencent.wework:id/au0")[0].send_keys(name)
        # 性别输入框
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='性别']/following-sibling::*").click()
        # 性别选择
        self.driver.find_elements(AppiumBy.ID, "com.tencent.wework:id/b2x")[0].click()
        # 手机号输入框
        self.driver.find_element(AppiumBy.ID, "com.tencent.wework:id/eq7").send_keys(phone_number)
        # 点击保存
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='保存']").click()
        # 获取提示文本
        text = self.driver.find_element(AppiumBy.XPATH, "//*[@resource-id='com.tencent.wework:id/b_1']").text
        assert text == "手机已存在于通讯录，无法添加"
        # 点击弹框确定
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='确定']").click()
        # 点击返回
        self.driver.find_element(AppiumBy.XPATH, "//*[@resource-id='com.tencent.wework:id/gu_']").click()
        # 点击取消保存
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='取消']").click()
        # 点击返回通讯录页
        self.driver.find_element(AppiumBy.XPATH, "//*[@resource-id='com.tencent.wework:id/gu_']").click()

        # 通过adb命令强制关闭app

    def test_del_success(self):
        """数据清理,删除"""
        # 点击管理通讯录按钮
        self.driver.find_element(AppiumBy.XPATH, "//*[@resource-id='com.tencent.wework:id/gup']").click()
        self.swipe_find(element=f"//*[@text='{name}']")
        # 点击编辑按钮
        self.driver.find_element(AppiumBy.XPATH,
                                 f"//*[@text='{name}']/../../../..//following-sibling::*[@resource-id='com.tencent.wework:id/fcq']").click()
        # 点击删除成员
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='删除成员']").click()
        # 点击删除确定弹窗
        self.driver.find_element(AppiumBy.XPATH, "//*[@text='确定']").click()
        # 关闭管理通讯录，返回通讯录列表
        self.driver.find_element(AppiumBy.XPATH, "//*[@resource-id='com.tencent.wework:id/guk']").click()
        # 获取姓名列表
        name_list = []
        eles = self.driver.find_elements(AppiumBy.XPATH, "//*[@resource-id='com.tencent.wework:id/h14']/child::*")
        for ele in eles:
            text = ele.text
            name_list.append(text)
        # 去掉 "我的客户"
        name_list.pop(0)
        # 去掉 "添加成员"
        name_list.pop(len(name_list) - 1)
        print(name, name_list)
        assert name not in name_list

        pass

    def swipe_window(self):
        """滑动查找元素"""
        # 获取设备尺寸,返回字典
        size = self.driver.get_window_size()

        width = size.get("width")
        height = size.get('height')
        # 获取滑动操作的坐标值
        start_x = width / 2
        start_y = height * 0.8
        end_x = start_x
        end_y = height * 0.2
        # swipe(起始x坐标，起始y坐标，结束x坐标，结束y坐标，滑动时间（单位毫秒）)
        self.driver.swipe(start_x, start_y, end_x, end_y, 200)

    def swipe_find(self, element):
        '''
                滑动查找
                通过文本来查找元素，如果没有找到元素，就滑动，
                如果找到了，就返回元素
                '''
        # 为了滑动操作更快速，不用等待隐式等待设置的时间
        self.driver.implicitly_wait(1)
        for num in range(5):
            try:
                # 正常通过文本查找元素
                ele = self.driver.find_element(AppiumBy.XPATH, element)
                print("找到元素")
                # 能找到则把隐式等待恢复原来的时间
                self.driver.implicitly_wait(15)
                # 返回找到的元素对象
                return ele
            except Exception:
                # 当查找元素发生异常时
                print(f"没有找到元素，开始滑动")
                print(f"滑动第{num + 1}次")
                # 滑动操作
                self.swipe_window()
        # 把隐式等待恢复原来的时间
        self.driver.implicitly_wait(15)
        # 抛出找不到元素的异常
        raise NoSuchElementException(f"滑动之后，未找到 {element} 元素")
